/**
 * 带角色选择的320指令测试
 */

const WebSocket = require('ws');

async function test320WithRole() {
    console.log('🚀 开始测试320指令（带角色选择）...');

    return new Promise((resolve, reject) => {
        const ws = new WebSocket('ws://localhost:3000/user-service/websocket?t=9bb247dcf2597ecba186a3562c129f31');
        let step = 0;

        ws.on('open', () => {
            console.log('✅ WebSocket连接成功');

            // 步骤1: 查询角色列表
            console.log('📤 步骤1: 查询角色列表');
            ws.send(JSON.stringify({ c: 3, d: null }));
        });

        ws.on('message', (data) => {
            try {
                const response = JSON.parse(data.toString());
                console.log('📥 收到响应:', JSON.stringify(response, null, 2));

                if (step === 0 && response.act_id === 3) {
                    // 角色列表查询完成
                    if (response.roleList && response.roleList.length > 0) {
                        const character = response.roleList[0];
                        console.log(`✅ 找到角色: ${character.name} (ID: ${character.id})`);

                        // 步骤2: 选择角色
                        step = 1;
                        console.log('📤 步骤2: 选择角色');
                        ws.send(JSON.stringify({
                            c: 4,
                            d: { characterId: character.id }
                        }));
                    } else {
                        console.log('❌ 没有找到角色');
                        ws.close();
                        resolve(response);
                    }
                } else if (step === 1 && response.act_id === 4) {
                    // 角色选择完成
                    if (response.code === 0) {
                        console.log('✅ 角色选择成功');

                        // 步骤3: 发送320指令
                        step = 2;
                        console.log('📤 步骤3: 发送320指令');
                        ws.send(JSON.stringify({ c: 320 }));
                    } else {
                        console.log('❌ 角色选择失败:', response.msg);
                        ws.close();
                        resolve(response);
                    }
                } else if (step === 2 && response.act_id === 320) {
                    // 320指令响应
                    if (response.code === 0) {
                        console.log('✅ 320指令执行成功');
                        console.log(`📊 上阵副将数量: ${response.list ? response.list.length : 0}`);

                        if (response.list && response.list.length > 0) {
                            console.log('📋 上阵副将列表:');
                            response.list.forEach((deputy, index) => {
                                const gender = deputy.sex === 1 ? '男' : '女';
                                console.log(`  ${index + 1}. ID:${deputy.id} 头像:${deputy.headImg} 职业:${deputy.roleType} 性别:${gender}`);
                            });
                        } else {
                            console.log('ℹ️ 当前没有上阵副将');
                        }
                    } else {
                        console.error('❌ 320指令执行失败:', response.msg);
                    }

                    ws.close();
                    resolve(response);
                }

            } catch (error) {
                console.error('❌ 解析响应失败:', error);
                ws.close();
                reject(error);
            }
        });

        ws.on('error', (error) => {
            console.error('❌ WebSocket错误:', error);
            reject(error);
        });

        ws.on('close', () => {
            console.log('🔌 WebSocket连接已关闭');
        });
    });
}

// 运行测试
if (require.main === module) {
    test320WithRole()
        .then(() => {
            console.log('🎉 测试完成');
            process.exit(0);
        })
        .catch((error) => {
            console.error('💥 测试失败:', error);
            process.exit(1);
        });
}

module.exports = { test320WithRole };
